package com.greatchn.no_session_auth_code.bean;

import cn.hutool.core.util.StrUtil;
import com.greatchn.no_session_auth_code.util.ApiAssert;
import com.greatchn.no_session_auth_code.web.po.UserInfo;
import com.greatchn.no_session_auth_code.web.srv.UserInfoSrv;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @CustomUserDetailsService: 自定义用户详情
 * @author: ZBoHang
 * @time: 2023/2/8 10:24
 */
@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private UserInfoSrv userInfoSrv;

    private final GrantedAuthority DEFAULT_ROLE = new SimpleGrantedAuthority("USER");

    @Override
    public UserDetails loadUserByUsername(String username) {
        // 查询用户
        UserInfo userInfo = this.userInfoSrv.findUserByUserName(username);
        ApiAssert.notNull(userInfo, "用户不存在!");
        // 设置角色
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>(12);
        String role = userInfo.getRole();
        // 角色属性为空时
        if(StrUtil.isBlank(role)){
            // 设置默认角色
            grantedAuthorities.add(DEFAULT_ROLE);
        }else{
            // 否则 得到账号对应的每个角色 并添加
            String [] roles = role.split(",");
            for (String r : roles){
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(r);
                grantedAuthorities.add(grantedAuthority);
            }
        }

        return new User(username, userInfo.getPassWord(), grantedAuthorities);
    }
}
